﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace Central.Linq.Mvc {
	/// <summary>
	/// Управлятор наборами фильтров
	/// </summary>
#if !DEBUG

	[DebuggerStepThrough]
#endif
	public sealed class PreparableFiltersManager {
		private IList<PreparableFilters> _items;

		public PreparableFiltersManager() {
			this._items = new List<PreparableFilters>();
		}

		public void Add(PreparableFilters filters) {
			this._items.Add(filters);
		}

		public void Add(string userName, string controllerName, string actionName, IList<FilterDefinition> filters) {
			this._items.Add(new PreparableFilters(userName, controllerName, actionName, filters));
		}

		public void Add(string userName, string controllerName, string actionName, FilterDefinition filter) {
			PreparableFilters _filter = this.Filters(userName, controllerName, actionName);
			if (_filter != null) {
				_filter.ActionFilters.Add(filter);
			}
			else {
				PreparableFilters newFilters = new PreparableFilters(userName, controllerName, actionName);
				newFilters.ActionFilters.Add(filter);
				this._items.Add(newFilters);
			}
		}

		public PreparableFilters Filters(string userName, string controllerName, string actionName) {
			var result = _items.SingleOrDefault(x => x.UserName.Equals(
				userName, StringComparison.InvariantCultureIgnoreCase)
				&& x.ActionName.Equals(actionName, StringComparison.InvariantCultureIgnoreCase)
				&& x.ControllerName.Equals(controllerName, StringComparison.InvariantCultureIgnoreCase
				));
			return result;
		}

		public bool DeleteFilter(string userName, string controllerName, string actionName, string id) {
			Guid _id = Guid.Parse(id);
			PreparableFilters _filter = this.Filters(userName, controllerName, actionName);
			FilterDefinition filter = _filter.ActionFilters.SingleOrDefault(x => x.Id.Equals(_id));
			if (filter != null) {
				_filter.ActionFilters.Remove(filter);
				return true;
			}
			return false;
		}
	}
}